package com.zkingsoft.wechat;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.matrix.core.tools.LogUtil;
import com.matrix.core.web.BaseAction;
import com.zkingsoft.bean.BizUser;
import com.zkingsoft.redis.RedisUserLoginUtils;
import com.zkingsoft.service.BizUserService;

/**
 * 认证类
 * @Description:   
 * @author: xiaochonggao
 * @date:   2018年5月29日 上午7:57:27 
 * @version V1.0
 */
@Controller
@RequestMapping(value = "wxapi/auth")
public class WxAuthAction extends BaseAction {

	@Autowired
	private BizUserService bizUserService;

	@Autowired
	RedisUserLoginUtils redisUserLoginUtils;

	/**
	 * 文件上传
	 * @author xiaochonggao
	 * @email 760568680@qq.com
	 * @date 2018年5月29日
	 * @param bizUser
	 * @return
	 */
	@RequestMapping(value = "/upload")
	public void upload(HttpServletRequest request, HttpServletResponse response) {

		BizUser loginUser = redisUserLoginUtils.getLoginUser();
		//获取文件需要上传到的路径
        String path = request.getRealPath("/upload") + "/";
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdir();
        }
        LogUtil.info("路径={}", path);

        try {
			request.setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException e2) {
			e2.printStackTrace();
		}  //设置编码
        //获得磁盘文件条目工厂
        DiskFileItemFactory factory = new DiskFileItemFactory();

        //如果没以下两行设置的话,上传大的文件会占用很多内存，
        //设置暂时存放的存储室,这个存储室可以和最终存储文件的目录不同
        factory.setRepository(dir);
        //设置缓存的大小，当上传文件的容量超过该缓存时，直接放到暂时存储室
        factory.setSizeThreshold(1024 * 1024);
        //高水平的API文件上传处理
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            List<FileItem> list = upload.parseRequest(request);
            FileItem picture = null;
            for (FileItem item : list) {
                //获取表单的属性名字
                String name = item.getFieldName();
                //如果获取的表单信息是普通的 文本 信息
                if (item.isFormField()) {
                    //获取用户具体输入的字符串
                    String value = item.getString();
                    request.setAttribute(name, value);
                    LogUtil.info("name={},value={}", path,value);
                } else {
                    picture = item;
                }
            }

            //自定义上传图片的名字为userId.jpg
            String fileName = request.getAttribute("userId") + ".jpg";
            String destPath = path + fileName;
            LogUtil.info("destPath={}", destPath);

            //真正写到磁盘上
            File file = new File(destPath);
            OutputStream out = new FileOutputStream(file);
            InputStream in = picture.getInputStream();
            int length = 0;
            byte[] buf = new byte[1024];
            // in.read(buf) 每次读到的数据存放在buf 数组中
            while ((length = in.read(buf)) != -1) {
                //在buf数组中取出数据写到（输出流）磁盘上
                out.write(buf, 0, length);
            }
            in.close();
            out.close();
        } catch (FileUploadException e1) {
            e1.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
		try {
			PrintWriter printWriter = response.getWriter();
			response.setContentType("application/json");
	        response.setCharacterEncoding("utf-8");
	        HashMap<String, Object> res = new HashMap<String, Object>();
	        res.put("success", true);
	        printWriter.write(JSON.toJSONString(res));
	        printWriter.flush();  
		} catch (IOException e) {
			e.printStackTrace();
		}
        
	}
}